import os

from google.appengine.ext import db
from google.appengine.ext.webapp import template

from model import Author, Picture

from tools import manager

class AuthorManager(manager.Manager):
    """
    """

    def get_author_key(self, name):
        """
        """
        #
        split_name = name.split(' ')

        #
        first_name = split_name[1]
        if first_name == '':
            first_name = ' '

        #
        last_name = split_name[0]
        if last_name == '':
            last_name = ' '

        #
        query = Author.all()
        query.filter('language =', self.language)
        query.filter('first_name =', first_name)
        query.filter('last_name =', last_name)
        #
        if query.count() == 0:
            query = Author.all()
            query.filter('language =', self.language)
            query.order('last_name')
            query.order('first_name')

        # get the author
        author = query.get()
        if author:
            return author.key()

        # try to get the fisrt
        else:
            return None

    def get_default_author(self):
        # find the default author
        author_query = Author().all()
        author_query.filter('language =', self.language)
        author_query.filter('first_name =', ' ')
        author_query.filter('last_name =', ' ')
        # get the default
        author = author_query.get()
        # if no default we create one
        if not author:
            author_key = self.new()
            author = Author().get(author_key)
        #return the default author
        return author

    def get_menu(self, edit=False):
        """
        """
        # get all authors
        query = Author.all()
        query.filter('language =', self.language)
        query.order('last_name')
        query.order('first_name')

        # init menu
        menu = list()
        list_authors = list()

        # we sort by char
        current_char = None

        # set the menu content
        for author in query:

            # test the current char
            if author.last_name[:1] != current_char:

                #
                if current_char and len(list_authors) > 0:

                    # set a dict with the char and corresponding name list
                    item_char = {
                                'char': current_char,
                                'authors': list_authors}

                    # add the dict into the menu
                    menu.append(item_char)

                # new current char we update
                current_char = author.last_name[:1]

                # list of authors for a category
                list_authors = list()

            last_name = author.last_name.strip()
            first_name = author.first_name.strip()
            if last_name == '' and first_name == '':
                if edit:
                    #
                    list_authors.append(author)
                else:
                    pass
            else:
                #
                list_authors.append(author)

        if len(list_authors) > 0:
            # set the last dict
            item_char = {
                        'char': current_char,
                        'authors': list_authors}

            # add the dict into the menu
            menu.append(item_char)

        # return the menu at the end
        return menu

    def show(self, author_key=None):
        """
        """
        if not author_key:
            #
            author_key = self.new()

        # get the menu at first
        menu = self.get_menu()
        #
        author = Author().get(author_key)
        # update max size
        if author.html_info:
            author.html_info = author.html_info.replace('max_size=',
                        'max_size=%s' % self.size.width)

        # set the template
        self.template_values['action'] = 'author'
        self.template_values['menu'] = menu
        self.template_values['author'] = author

        # find the template
        path = os.path.join(os.path.dirname(__file__),
                                '../templates', 'author', 'index.html')

        # display the author
        return template.render(path, self.template_values)

    def edit(self, author_key):
        """
        """
        # get the menu at first
        menu = self.get_menu(edit=True)
        # get the author
        author = Author().get(author_key)

        # set the template
        self.template_values['menu'] = menu
        self.template_values['author'] = author
        self.template_values['page'] = 'author'
        self.template_values['images'] = self.get_content_images()

        # find the template
        path = os.path.join(os.path.dirname(__file__),
                            '../templates', 'author', 'edit.html')

        # display the author
        return template.render(path, self.template_values)

    def new(self):
        """
        """
        # create the new author
        author = Author()

        # requirement
        author.first_name = db.Category(' ')

        # requirement
        author.last_name = db.Category(' ')

        # set the current language
        author.language = self.language

        #
        author.put()

        return author.key()

    def delete(self, author_key):
        """
        """
        #
        author = Author().get(author_key)

        # get corresponding pictures
        query = Picture().all()
        query.filter('author =', author)

        # delete relation from picture
        for picture in query:
            picture.author = None
            picture.put()

        # delete the author
        author.delete()

    def save(self, author_key, first_name, last_name, info):
        """
        """
        #
        author = Author().get(author_key)

        # first_name can t be empty
        first_name = first_name.strip()
        if first_name == '':
            first_name = ' '

        # last_name can t be empty
        last_name = last_name.strip()
        if last_name == '':
            last_name = ' '

        # set first_name
        author.first_name = db.Category(first_name)

        # set last_name
        author.last_name = db.Category(last_name)

        # set info
        author.info = info
        author.html_info = self.get_html_content(info)

        # save author
        author.put()
